<template>
  <div class="wrong-question-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-area">
      <div class="filter-header">
        <h2 style="color: #2c5282;">我的错题</h2>
        <div class="filter-actions">
          <el-button type="primary" size="small" @click="handleFilter">
            <el-icon><Search /></el-icon> 筛选
          </el-button>
          <el-button size="small" @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </div>
      </div>

      <div class="filter-content">
        <!-- 课程+知识点级联选择 -->
        <div class="filter-row">
          <div class="filter-label" style="margin-right: 16px;">课程与知识点</div>
          <el-cascader
            v-model="selectedCourseAndKnowledge"
            :options="courseKnowledgeOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择课程和知识点"
            @change="handleCourseKnowledgeChange"
            class="filter-input"
          />
        </div>

        <!-- 时间筛选 -->
        <div class="filter-row">
          <div class="filter-label">时间范围</div>
          <el-date-picker
            v-model="timeRange"
            type="monthrange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :shortcuts="timeShortcuts"
            class="filter-input"
          />
        </div>

        <!-- 掌握状态筛选 -->
        <div class="filter-row">
          <div class="filter-label">掌握状态</div>
          <el-select
            v-model="masteryStatus"
            placeholder="请选择掌握状态"
            clearable
            class="filter-input"
          >
            <el-option label="未掌握" :value="0" />
            <el-option label="已掌握" :value="1" />
          </el-select>
        </div>

        <!-- 来源筛选 -->
        <div class="filter-row">
          <div class="filter-label">来源</div>
          <el-select
            v-model="sourceType"
            placeholder="请选择来源"
            clearable
            class="filter-input"
          >
            <el-option label="全部" :value="null" />
            <el-option label="练习" :value="1" />
            <el-option label="测试" :value="2" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 错题列表区域 -->
    <div class="question-list-area">
      <div class="list-header">
        <div class="header-left">
          <span class="total-count">共 {{ totalQuestions }} 道错题</span>
          <el-tag type="info" size="small">未掌握 {{ unmasteredCount }} 道</el-tag>
          <el-tag type="success" size="small">已掌握 {{ masteredCount }} 道</el-tag>
        </div>
        <div class="header-right">
          <el-button-group>
            <el-button size="small" :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
              <el-icon><Menu /></el-icon> 列表
            </el-button>
            <el-button size="small" :type="viewMode === 'card' ? 'primary' : ''" @click="viewMode = 'card'">
              <el-icon><Grid /></el-icon> 卡片
            </el-button>
          </el-button-group>
          <el-button
            size="small"
            type="success"
            :disabled="filteredQuestions.length === 0"
            @click="practiceAllFiltered"
          >
            去练习全部
          </el-button>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="list-view">
        <el-table :data="filteredQuestions" style="width: 100%" height="500" border stripe>
          <el-table-column prop="courseName" label="课程" width="120" />
          <el-table-column prop="pointName" label="知识点" width="180" />
          <el-table-column prop="questionContent" label="题目">
            <template #default="{ row }">
              <div class="question-content" v-html="row.questionContent"></div>
            </template>
          </el-table-column>
          <el-table-column prop="wrongCount" label="错误次数" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.wrongCount > 3 ? 'danger' : 'warning'" size="small">
                {{ row.wrongCount }}次
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastWrongTime" label="最近错误" width="120" align="center" />
          
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                class="practice-btn"
                @click="handlePractice(row)"
      >
        <el-icon><Edit /></el-icon> 练习
      </el-button>
    </template>
  </el-table-column>
        </el-table>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <el-row :gutter="20">
          <el-col :span="8" v-for="question in filteredQuestions" :key="question.id" class="card-col">
            <el-card class="question-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="course-tag">{{ question.courseName }}</span>
                  <span class="knowledge-tag">{{ question.pointName }}</span>
                  <el-tag :type="question.isMastered ? 'success' : 'danger'" size="small" class="mastery-tag">
                    {{ question.isMastered ? '已掌握' : '未掌握' }}
                  </el-tag>
                </div>
              </template>
              <div class="card-content">
                <div class="question-text" v-html="question.questionContent"></div>
                <div class="question-meta">
                  <span class="wrong-count">
                    <el-icon><Warning /></el-icon> {{ question.wrongCount }}次
                  </span>
                  <span class="last-time">
                    <el-icon><Clock /></el-icon> {{ question.lastWrongTime }}
                  </span>
                  <span class="source">
                    <el-icon><Document /></el-icon> {{ question.sourceType === 1 ? '练习' : '测试' }}
                  </span>
                </div>
              </div>
              <div class="card-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  class="practice-btn"
                  @click="handlePractice(question)"
                >
                  <el-icon><Edit /></el-icon> 练习
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalQuestions"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 假设你用的是 <script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

function goToMistakesReview() {
  router.push({ name: 'MistakesReview' })
}
import { ref, computed, onMounted, watch } from 'vue'
import type { CascaderProps } from 'element-plus'
import {
  Search,
  Refresh,
  Menu,
  Grid,
  Download,
  Edit,
  Delete,
  Warning,
  Clock,
  Document,
  CircleCheck
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

// 时间快捷选项
const timeShortcuts = [
  {
    text: '本月',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), end.getMonth(), 1)
      return [start, end]
    }
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), end.getMonth() - 2, 1)
      return [start, end]
    }
  }
]

// 课程、知识点、错题数据
const courseKnowledgeOptions = ref<any[]>([])
const cascaderProps: CascaderProps = {
  checkStrictly: true,
  expandTrigger: 'hover'
}

// 表单数据
const selectedCourseAndKnowledge = ref([])
const timeRange = ref('')
const masteryStatus = ref<number | null>(null)
const sourceType = ref<number | null>(null)
const viewMode = ref<'list' | 'card'>('list')

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalQuestions = ref(0)

// 错题数据
const allQuestions = ref<any[]>([])

// 用户信息
const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId)

// 课程、知识点初始化
const fetchCoursesAndPoints = async () => {
  const courseRes = await axios.get('http://localhost:8080/Courses/all')
  const courses = courseRes.data
  // 并发获取每门课的知识点
  const cascaderData = await Promise.all(
    courses.map(async (course: any) => {
      const kpRes = await axios.get('http://localhost:8080/KnowledgePoint/course', { params: { courseId: course.courseId } })
      return {
        value: course.courseId,
        label: course.courseName,
        children: kpRes.data.map((kp: any) => ({
          value: kp.pointId,
          label: kp.pointName
        }))
      }
    })
  )
  courseKnowledgeOptions.value = cascaderData
}

// 查询错题
const fetchWrongQuestions = async () => {
  let params: any = {
    page: currentPage.value,
    size: pageSize.value,
    userId: userId.value // 添加用户ID
  }
  if (userId.value) {
    params.userId = userId.value
  }
  if (selectedCourseAndKnowledge.value.length > 0) {
    params.courseId = selectedCourseAndKnowledge.value[0]
    if (selectedCourseAndKnowledge.value.length > 1) {
      params.pointId = selectedCourseAndKnowledge.value[1]
    }
  }
  if (timeRange.value && timeRange.value.length === 2) {
    params.startTime = timeRange.value[0]
    params.endTime = timeRange.value[1]
  }
  if (masteryStatus.value !== null) {
    params.isMastered = masteryStatus.value
  }
  if (sourceType.value !== null) {
    params.sourceType = sourceType.value
  }
  // 你需要实现后端 /wrongquestions/query 支持这些参数
  const res = await axios.get('http://localhost:8080/wrongquestions/query', { params });
  console.log('API返回数据:', res.data); // 检查返回的数据结构
  console.log('第一条记录:', res.data.records[0]); // 检查第一条记录的字段
  allQuestions.value = res.data.records
  totalQuestions.value = res.data.total
}

// 计算已掌握和未掌握数量
const masteredCount = computed(() => allQuestions.value.filter(q => q.isMastered === 1).length)
const unmasteredCount = computed(() => allQuestions.value.filter(q => q.isMastered === 0).length)

// 筛选后的错题列表（分页已由后端处理）
const filteredQuestions = computed(() => allQuestions.value)

// 监听筛选条件变化自动查询
// 监听筛选条件变化自动查询（加入 userId 监听）
watch([
  selectedCourseAndKnowledge,
  timeRange,
  masteryStatus,
  sourceType,
  currentPage,
  pageSize,
  userId
], fetchWrongQuestions)

// 课程知识点选择变化
const handleCourseKnowledgeChange = () => {
  // 可以根据需要在此处理逻辑，比如自动刷新错题列表
  // fetchWrongQuestions()
}

// 筛选按钮
const handleFilter = () => {
  currentPage.value = 1
  fetchWrongQuestions()
}

// 重置按钮
const handleReset = () => {
  selectedCourseAndKnowledge.value = []
  timeRange.value = ''
  masteryStatus.value = null
  sourceType.value = null
  currentPage.value = 1
  fetchWrongQuestions()
}

// 分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchWrongQuestions()
}
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchWrongQuestions()
}

// 批量练习筛选出来的所有错题
const practiceAllFiltered = () => {
  if (filteredQuestions.value.length === 0) {
    ElMessage.warning('没有可练习的错题')
    return
  }
  const ids = filteredQuestions.value.map(q => q.id).join(',') // 注意这里用错题表的id
  router.push({ name: 'PracticeMistakes', query: { wrongQuestionIds: ids } })
}

// 单题练习
const handlePractice = (question: any) => {
  router.push({ name: 'PracticeMistakes', query: { wrongQuestionIds: question.id } })
}

// 删除错题
const handleDelete = async (question: any) => {
  await axios.get('http://localhost:8080/wrongquestions/softdelete', { params: { id: question.id } })
  ElMessage.success('错题删除成功')
  fetchWrongQuestions()
}

// 切换掌握状态
const handleMasteryChange = async (question: any) => {
  console.log('提交参数', { id: question.id, isMastered: question.isMastered });
  try {
    const response = await axios.post('http://localhost:8080/wrongquestions/update', {
      id: question.id,
      isMastered: question.isMastered
    });
    console.log('API响应:', response.data);
    ElMessage.success(`已${question.isMastered ? '标记为掌握' : '取消掌握'}`);
    fetchWrongQuestions();
  } catch (error) {
    console.error('更新掌握状态失败:', error);
    // 恢复原来的状态
    question.isMastered = question.isMastered ? 0 : 1;
    ElMessage.error('更新掌握状态失败');
  }
}

// 卡片视图切换掌握状态
const handleMasteryToggle = async (question: any) => {
  const originalStatus = question.isMastered;
  question.isMastered = question.isMastered ? 0 : 1; // 先更新本地状态
  try {
    await handleMasteryChange(question);
  } catch (error) {
    question.isMastered = originalStatus; // 出错时恢复状态
  }
}

// 导出错题
const exportWrongQuestions = () => {
  ElMessage.success('导出功能正在开发中')
}

// 初始化
onMounted(() => {
  fetchCoursesAndPoints()
  // 如果 userId 已经有值，直接查；否则等 userId 变化再查
  if (userId.value) {
    fetchWrongQuestions()
  } else {
    const stop = watch(userId, (val) => {
      if (val) {
        fetchWrongQuestions()
        stop()
      }
    })
  }
})
</script>

<style scoped lang="scss">
/* 统一按钮样式 */
.practice-btn {
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 14px;
  height: 36px;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(74, 144, 226, 0.2);
  }
  
  &:active {
    transform: translateY(0);
  }
  
  .el-icon {
    margin-right: 6px;
    font-size: 16px;
  }
}

/* 确保卡片视图中的按钮与其他按钮一致 */
.card-actions {
  .el-button {
    border-radius: 8px;
    padding: 8px 12px;
    font-size: 14px;
    height: 36px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    &:active {
      transform: translateY(0);
    }
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
    }
    
    /* 主按钮样式 */
    &.el-button--primary {
      background: #4a90e2;
      color: white;
      border: none;
      
      &:hover {
        background: #3a7bc8;
      }
    }
    
    /* 成功按钮样式 */
    &.el-button--success {
      background: #48a6bb;
      color: white;
      border: none;
      
      &:hover {
        background: #38a19c;
      }
    }
  }
}

/* 列表视图中的按钮调整 */
.list-view {
  :deep(.el-table) {
    .el-button {
      border-radius: 8px;
      padding: 8px 12px;
      font-size: 14px;
      height: 36px;
      
      .el-icon {
        margin-right: 6px;
        font-size: 16px;
      }
    }
  }
}

/* 顶部操作按钮样式统一 */
.filter-actions, .header-right {
  .el-button {
    border-radius: 8px;
    padding: 8px 12px;
    font-size: 14px;
    height: 36px;
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
    }
  }
}

.wrong-question-container {
  padding: 24px 10px 24px 10px;
  background: linear-gradient(135deg, #e7eef9 0%, #cae0f8 100%);
  min-height: 100vh;
  position: relative;
}

.filter-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 28px 32px 22px 32px;
  margin-bottom: 28px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #d4e6f7;
  position: relative;
  z-index: 1;
  
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 22px;
      color: #2c5282;
      font-weight: 600;
    }
    
    .filter-actions {
      display: flex;
      gap: 12px;
      
      .el-button {
        border-radius: 8px;
        font-size: 14px;
        min-width: 70px;
        height: 36px;
        background: #f0f8ff;
        color: #4a90e2;
        border: 1px solid #d4e6f7;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(74, 144, 226, 0.1);
          color: #3a7bc8;
          transform: translateY(-2px);
        }
      }
    }
  }
  
  .filter-content {
    display: flex;
    gap: 22px;
    max-width: 1100px;
    margin: 0 auto;
    flex-wrap: wrap;
  }
  
  .filter-row {
    display: flex;
    align-items: center;
    min-width: 0;
    margin-right: 10px;
    
    .filter-label {
      width: 80px;
      font-size: 14px;
      color: #4a5568;
      white-space: nowrap;
      margin-right: 2px;
      font-weight: 500;
    }
    
    .filter-input {
      flex: 1;
      min-width: 140px;
      max-width: 300px;
      width: 200px;
      background: #fff;
      border-radius: 8px;
      
      :deep(.el-select) {
        width: 100% !important;
      }
      
      :deep(.el-input__inner) {
        width: 100% !important;
        border-color: #d4e6f7;
        
        &:focus {
          border-color: #4a90e2;
        }
      }
    }
  }
}

.question-list-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 28px 22px 22px 22px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #d4e6f7;
  position: relative;
  z-index: 1;
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 22px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .total-count {
        font-size: 15px;
        color: #4a5568;
        font-weight: 500;
      }
      
      .el-tag {
        border-radius: 8px;
        font-size: 13px;
        padding: 0 10px;
        background: #f0f8ff;
        color: #4a90e2;
        border: 1px solid #d4e6f7;
      }
    }
    
    .header-right {
      display: flex;
      align-items: center;
      gap: 14px;
      
      .el-button {
        border-radius: 8px;
        font-size: 14px;
        min-width: 70px;
        height: 36px;
        background: #f0f8ff;
        color: #4a90e2;
        border: 1px solid #d4e6f7;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(74, 144, 226, 0.1);
          color: #3a7bc8;
          transform: translateY(-2px);
        }
        
        &.el-button--primary {
          background: #4a90e2;
          color: white;
          
          &:hover {
            background: #3a7bc8;
          }
        }
        
        &.el-button--success {
          background: #4dace3;
          color: white;
          
          &:hover {
            background: #3867a1;
          }
        }
      }
    }
  }
  
  .list-view {
    :deep(.el-table) {
      background: transparent;
      border-radius: 8px;
      
      .question-content {
        line-height: 1.5;
      }
      
      .el-table__cell {
        padding: 10px 0;
      }
      
      .el-button + .el-button {
        margin-left: 14px !important;
      }
      
      .el-tag {
        border-radius: 8px;
      }
    }
  }
  
  .card-view {
    .card-col {
      margin-bottom: 28px;
    }
    
    .question-card {
      height: 100%;
      border-radius: 15px;
      background: #fff;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
      border: 1px solid #d4e6f7;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        border-color: #4a90e2;
      }
      
      :deep(.el-card__header) {
        padding: 16px 20px 12px 20px;
        border-radius: 15px 15px 0 0;
        background: #f0f8ff;
        border-bottom: 1px solid #d4e6f7;
      }
      
      .card-header {
        display: flex;
        align-items: center;
        gap: 10px;
        
        .course-tag {
          background-color: #ebf8ff;
          color: #3182ce;
          padding: 2px 10px;
          border-radius: 8px;
          font-size: 13px;
          font-weight: 500;
          border: 1px solid #bee3f8;
        }
        
        .knowledge-tag {
          background-color: #f0fff4;
          color: #3870a1;
          padding: 2px 10px;
          border-radius: 8px;
          font-size: 13px;
          font-weight: 500;
          border: 1px solid #c6f6d5;
        }
        
        .mastery-tag {
          margin-left: auto;
          border-radius: 8px;
          font-size: 13px;
          padding: 0 10px;
        }
      }
      
      .card-content {
        .question-text {
          margin-bottom: 14px;
          line-height: 1.6;
          font-size: 15px;
          color: #4a5568;
        }
        
        .question-meta {
          display: flex;
          justify-content: space-between;
          font-size: 13px;
          color: #718096;
          
          span {
            display: flex;
            align-items: center;
            gap: 6px;
          }
        }
      }
      
      .card-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 14px;
        
        .el-button {
          border-radius: 8px;
          font-size: 14px;
          min-width: 70px;
          height: 36px;
          transition: all 0.3s ease;
          
          &.el-button--primary {
            background: #4a90e2;
            color: white;
            border: none;
            
            &:hover {
              background: #3a7bc8;
              transform: translateY(-2px);
            }
          }
          
          &.el-button--success {
            background: #486ebb;
            color: white;
            border: none;
            
            &:hover {
              background: #385da1;
              transform: translateY(-2px);
            }
          }
        }
      }
    }
  }
  
  .pagination {
    margin-top: 28px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .filter-content {
    grid-template-columns: 1fr !important;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: flex-start !important;
    
    .filter-label {
      margin-bottom: 8px;
      width: 100% !important;
    }
    
    .filter-input {
      width: 100%;
    }
  }
  
  .list-header {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 12px;
    
    .header-right {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .card-col {
    width: 100% !important;
  }
}
</style>